11. db.Model and Defining Models

db.Model and defining models

ND004 C01 L03 11 SQLAlchemy(App) Db.Model And Db.Create All()

Takeaways

Given an instance of the SQLAlchemy class from Flask-SQLAlchemy,

db = SQLAlchemy(app)
  • db is an interface for interacting with our database
  • db.Model lets us create and manipulate data models
  • db.session lets us create and manipulate database transactions

Hello App with Flask-SQLAlchemy continued

Creating a person class with db.Model

ND004 C01 L03 11.1 SQLAlchemy(App) Db.Model And Db.Create All()

Takeaways

Declaring classes
  • class MyModel(db.Model) will inherit from db.Model
  • By inheriting from db.Model , we map from our classes to tables via SQLAlchemy ORM
Defining columns
  • Within our class, we declare attributes equal to db.Column(...)
  • db.Column takes <datatype>, <primary_key?>, <constraint?>, <default?>
Table naming
  • By default, SQLAlchemy will pick the name of the table for you, setting it equal to the lower-case version of your class's name. Otherwise, we set the name of the table using __tablename__ = 'my_custom_table_name' .

Code

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://udacitystudios@localhost:5432/example'
db = SQLAlchemy(app)

class Person(db.Model):
  __tablename__ = 'persons'
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.String(), nullable=False)